const winston = require('winston');
const path = require('path');
const config = require('../config/config');

const setupLogger = () => {
  const logger = winston.createLogger({
    level: config.logging.level,
    format: winston.format.combine(
      winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
      }),
      winston.format.errors({ stack: true }),
      winston.format.json()
    ),
    defaultMeta: { service: 'crypto-aggregator' },
    transports: [
      // 写入所有日志到文件
      new winston.transports.File({
        filename: path.resolve(config.logging.file),
        maxsize: config.logging.maxSize,
        maxFiles: config.logging.maxFiles,
        tailable: true
      }),
      // 错误日志单独文件
      new winston.transports.File({
        filename: path.resolve('./logs/error.log'),
        level: 'error',
        maxsize: config.logging.maxSize,
        maxFiles: config.logging.maxFiles,
        tailable: true
      })
    ]
  });

  // 开发环境下同时输出到控制台
  if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    }));
  }

  return logger;
};

module.exports = { setupLogger };

